<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import { loginApi } from '@/api/login'
import { useRouter, useRoute } from 'vue-router'
// 不再导入图标组件，使用Element Plus内置的图标名称字符串

const router = useRouter()
const route = useRoute()

// 登录数据
const loginForm = reactive({
  username: '',
  password: '',
  rememberMe: false
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应为3-20个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/, message: '用户名只能包含字母、数字、下划线和中文', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20个字符', trigger: 'blur' }
  ]
}

// 表单引用
const loginFormRef = ref(null)

// 密码可见性控制
const showPassword = ref(false)
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value
}

// 登录加载状态
const loading = ref(false)

// 错误提示状态
const usernameError = ref('')
const passwordError = ref('')

// 忘记密码处理
const handleForgotPassword = () => {
  ElMessage({
    message: '忘记密码功能暂未开放，请联系管理员',
    type: 'info'
  })
}

// 登录
const handleLogin = async () => {
  // 表单验证
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    
    loading.value = true
    const result = await loginApi(loginForm)
    
    if (result.code === 1) {
      // 保存token和用户信息
      localStorage.setItem('token', result.data.token)
      localStorage.setItem('userInfo', JSON.stringify(result.data))
      
      // 处理记住用户名功能
      if (loginForm.rememberMe) {
        localStorage.setItem('rememberedUsername', loginForm.username)
      } else {
        localStorage.removeItem('rememberedUsername')
      }
      
      ElNotification({
        title: '成功',
        message: '登录成功，欢迎回来！',
        type: 'success',
        duration: 2000
      })
      
      // 处理重定向逻辑
      const redirectPath = route.query.redirect || '/home'
      // 延迟跳转以显示成功提示
      setTimeout(() => {
        router.push(redirectPath)
      }, 1000)
    } else {
      ElMessage.error(result.msg || '登录失败，请检查用户名或密码')
    }
  } catch (error) {
    if (error.name === 'Error') {
      // 业务错误
      ElMessage.error('登录失败，请检查网络连接')
      console.error('登录错误:', error)
    }
    // 表单验证错误由element-plus自动处理
  } finally {
    loading.value = false
  }
}

// 处理键盘回车登录
const handleKeydown = (e) => {
  if (e.key === 'Enter') {
    handleLogin()
  }
}

// 组件挂载时，检查是否有记住的用户名
onMounted(() => {
  const rememberedUsername = localStorage.getItem('rememberedUsername')
  if (rememberedUsername) {
    loginForm.username = rememberedUsername
    loginForm.rememberMe = true
  }
  
  // 自动聚焦到用户名输入框
  setTimeout(() => {
    const usernameInput = document.querySelector('input[placeholder="请输入用户名"]')
    if (usernameInput) usernameInput.focus()
  }, 100)
})
</script>

<template>
  <div class="login-container" @keydown="handleKeydown">
    <div class="login-form-wrapper">
      <div class="login-form-header">
        <div class="logo-box">
          <el-icon class="logo-icon">
            <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" width="40" height="40">
              <path d="M512 128c-211.7 0-384 172.3-384 384s172.3 384 384 384 384-172.3 384-384S723.7 128 512 128zm0 640c-141.4 0-256-114.6-256-256s114.6-256 256-256 256 114.6 256 256-114.6 256-256 256zm-96-320c0-17.7 14.3-32 32-32s32 14.3 32 32v128c0 17.7-14.3 32-32 32s-32-14.3-32-32V448z"/>
            </svg>
          </el-icon>
        </div>
        <h2 class="title">企业管理系统</h2>
        <p class="subtitle">请输入账号密码登录</p>
      </div>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="rules"
        class="login-form"
        label-position="left"
        size="large"
        :validate-on-rule-change="false"
      >
        <el-form-item 
          prop="username"
        >
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            autocomplete="off"
            clearable
            :disabled="loading"
          >
            <template #prefix>
              <el-icon class="el-input__icon" color="#606266">
                <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                  <path d="M512 128c-211.7 0-384 172.3-384 384s172.3 384 384 384 384-172.3 384-384S723.7 128 512 128zm0 640c-141.4 0-256-114.6-256-256s114.6-256 256-256 256 114.6 256 256-114.6 256-256 256z"/>
                  <path d="M512 320c-64.2 0-116 51.8-116 116s51.8 116 116 116 116-51.8 116-116-51.8-116-116-116z"/>
                </svg>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item 
          prop="password"
        >
          <el-input
            v-model="loginForm.password"
            :type="showPassword ? 'text' : 'password'"
            placeholder="请输入密码"
            autocomplete="off"
            clearable
            :disabled="loading"
          >
            <template #prefix>
              <el-icon class="el-input__icon" color="#606266">
                <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                  <path d="M832 464H712v-80c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v80H384v-80c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v80H192c-17.7 0-32 14.3-32 32v384c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V496c0-17.7-14.3-32-32-32zm-680 0h112v-80H152v80zm576 384H192V496h112v80c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8v-80h256v80c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8v-80h112v352z"/>
                  <path d="M512 480c-105.9 0-192 86.1-192 192s86.1 192 192 192 192-86.1 192-192-86.1-192-192-192zm0 320c-70.5 0-128-57.5-128-128s57.5-128 128-128 128 57.5 128 128-57.5 128-128 128z"/>
                </svg>
              </el-icon>
            </template>
            <template #suffix>
              <el-icon 
                :class="['el-input__icon', 'password-toggle']"
                @click="togglePasswordVisibility"
                color="#606266"
              >
                <svg v-if="showPassword" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                  <path d="M865.344 832l-41.6-41.6a64 64 0 0 0 0-90.496L557.248 456.512 466.56 365.824 105.984 25.6l-41.6 41.6 362.24 362.24 90.496 90.496 361.6 361.6zM512 660.992a148.992 148.992 0 1 0 0-297.984 148.992 148.992 0 0 0 0 297.984z"/>
                </svg>
                <svg v-else viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                  <path d="M946.5344 505.7536a709.504 709.504 0 0 1-196.992 339.6096C643.6096 886.2208 580.096 908.8 512 908.8c-68.096 0-131.6096-22.5792-188.352-63.488a705.92 705.92 0 0 1-196.992-339.6096 705.92 705.92 0 0 1 196.992-339.6096C380.3904 137.7792 443.904 115.2 512 115.2c68.096 0 131.6096 22.5792 188.352 63.488a705.92 705.92 0 0 1 196.992 339.6096zm-150.784-65.536a573.568 573.568 0 0 0-160.768-280.704C661.3504 163.328 601.472 144 512 144c-89.344 0-149.3504 19.328-202.944 55.552a576.512 576.512 0 0 0-160.768 280.704 576.512 576.512 0 0 0 160.768 280.704C362.6496 793.152 422.528 812.8 512 812.8c89.344 0 149.3504-19.648 202.944-55.552a573.568 573.568 0 0 0 160.768-280.704zM512 691.2a179.2 179.2 0 1 1 0-358.4 179.2 179.2 0 0 1 0 358.4zm0-256a76.8 76.8 0 1 0 0 153.6 76.8 76.8 0 0 0 0-153.6z"/>
                </svg>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item>
          <div class="login-form-extra">
            <el-checkbox 
              v-model="loginForm.rememberMe"
              size="large"
              :disabled="loading"
              class="remember-me"
            >
              记住用户名
            </el-checkbox>
            <el-button 
              type="text" 
              class="login-form-forgot"
              :disabled="loading"
            >
              忘记密码?
            </el-button>
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            class="login-button"
            :loading="loading"
            @click="handleLogin"
            :disabled="loading"
            size="large"
            block
          >
            <template v-if="loading">登录中...</template>
            <template v-else>登录</template>
          </el-button>
        </el-form-item>
        
        <div class="login-tips">
          <el-tag size="small" type="info" disable-transitions>
            提示：请使用管理员账号登录系统
          </el-tag>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  background-size: 100% 100%;
  background-attachment: fixed;
  position: relative;
  overflow: hidden;
}

/* 添加背景装饰 */
.login-container::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 1px, transparent 1px);
  background-size: 30px 30px;
  animation: moveBackground 20s linear infinite;
}

@keyframes moveBackground {
  0% {
    transform: translate(0, 0);
  }
  100% {
    transform: translate(30px, 30px);
  }
}

.login-form-wrapper {
  width: 420px;
  max-width: 90%;
  padding: 40px;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  position: relative;
  z-index: 1;
  transition: all 0.3s ease;
}

.login-form-wrapper:hover {
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.login-form-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo-box {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 80px;
  height: 80px;
  margin: 0 auto 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.logo-icon {
  font-size: 40px;
  color: white;
}

.title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.subtitle {
  font-size: 16px;
  color: #606266;
  margin: 0;
}

.login-form {
  width: 100%;
}

.login-form-extra {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.remember-me {
  font-size: 14px;
  color: #606266;
}

.login-form-forgot {
  font-size: 14px;
  color: #409eff;
  transition: color 0.3s;
}

.login-form-forgot:hover {
  color: #66b1ff;
}

.login-button {
  width: 100%;
  height: 50px;
  font-size: 18px;
  font-weight: 500;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
  transition: all 0.3s ease;
  margin-top: 10px;
}

.login-button:hover {
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.login-button:active {
  transform: translateY(0);
}

.login-tips {
  text-align: center;
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 24px;
}

.el-input {
  --el-input-bg-color: #fafafa;
  border-radius: 8px;
  transition: all 0.3s;
}

.el-input:hover {
  --el-input-bg-color: #f0f2f5;
}

.el-input__wrapper {
  border-radius: 8px;
}

.el-input__icon {
  font-size: 18px;
  transition: all 0.3s;
}

.password-toggle {
  cursor: pointer;
  padding: 0 8px;
  transition: all 0.3s;
}

.password-toggle:hover {
  color: #409eff !important;
  transform: scale(1.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-form-wrapper {
    width: 95%;
    padding: 30px 20px;
  }
  
  .title {
    font-size: 24px;
  }
  
  .logo-box {
    width: 60px;
    height: 60px;
  }
  
  .logo-icon {
    font-size: 30px;
  }
}

/* 动画效果 */
.login-form-wrapper {
  animation: fadeIn 0.6s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 输入框聚焦时的动画 */
.el-input:focus-within .el-input__wrapper {
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}
</style>